package com.shs.riggy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shs.riggy.common.R;
import com.shs.riggy.entity.Category;
import com.shs.riggy.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 晚点再动心
 * @Date 2022/9/12
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 保存
     *
     * @param category 类别
     * @return {@link R}<{@link String}>
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
       log.info("============执行新增菜品分类===============");
        categoryService.save(category);
        return R.success("新增菜品分类成功！");
    }

    /**
     * 分页
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @return {@link R}<{@link Page}>
     */
    @GetMapping("/page")
    //分页查询
    public R<Page> page(int page,int pageSize){
        //构造分页对象
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //构造条件查询器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort字段进行排序
        queryWrapper.orderByAsc(Category::getSort);
        //执行分页查询
        categoryService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    @DeleteMapping
    //菜品分类删除
    public R<String> delete( Long ids) {
        log.info("============根据id删除菜品分类==================");
        //LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //categoryService.removeById(id);
        categoryService.remove(ids);
        return R.success("删除菜品分类成功！");
    }

    /**
     * 修改分类列表信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("================修改分类信息为：{}===================",category);
        categoryService.updateById(category);
        return R.success("修改信息成功！");
    }

    //查询菜品分类信息pu
    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

        categoryLambdaQueryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        //排序條件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }
}
